package com.example.lib.muchthread;

/**
 * 等待唤醒demo优化
 */

class Res145 {
    private String name;
    private String sex;
    private boolean flag = false;

    public synchronized void set(String name, String sex) {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        this.name = name;
        this.sex = sex;
        flag = true;
        this.notify();
    }

    public synchronized void out() {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        flag = false;
        System.out.println(name + "..." + sex);
        this.notify();
    }
}

class Input145 implements Runnable {

    private Res145 res;

    public Input145(Res145 res) {
        this.res = res;
    }

    @Override
    public void run() {
        int x = 0;
        while (true) {
            if (x == 0) {
                res.set("mike", "man");
            } else {
                res.set("丽丽", "女");
            }
            x = (x + 1) % 2;
        }

    }
}

class Output145 implements Runnable {

    private Res145 res;

    public Output145(Res145 res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
               res.out();
        }
    }
}

public class o_thread_threadconn_145 {
    public static void main(String[] args) {
        Res145 res = new Res145();

        new Thread(new Input145(res)).start();
        new Thread(new Output145(res)).start();

//        Input145 input = new Input145(res);
//        Output145 output = new Output145(res);
//
//        Thread t1 = new Thread(input);
//        Thread t2 = new Thread(output);
//
//        t1.start();
//        t2.start();
    }
}

